package com.wocai.jrt.orgadmin.stats.service.impl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.inject.Inject;
import javax.inject.Named;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;

import com.wocai.jrt.admin.common.cache.Const;
import com.wocai.jrt.orgadmin.investor.dao.InvestorDao;
import com.wocai.jrt.orgadmin.investor.model.Investor;
import com.wocai.jrt.orgadmin.stats.bean.InvestorCountBean;
import com.wocai.jrt.orgadmin.stats.bean.PerFormReqBean;
import com.wocai.jrt.orgadmin.stats.service.spi.RedisCacheService;
import com.wocai.jrt.orgadmin.utils.City;
import com.wocai.jrt.orgadmin.utils.Province;


/**
 * 缓存控制器
 * @author zhangyz
 * @date 2015年10月13日17:23:50
 */
@Named
public class RedisCacheServiceImpl implements RedisCacheService {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(RedisCacheServiceImpl.class);
	@Inject
	 private InvestorDao investorDao;
	/**
	 * 保存投资人统计数据到缓存
	 */
	@Override
	public Map<String, Object> saveInvestorCache(Map<String, Object> map,String key) {
		LOGGER.info("save Investor Stats Cache");
		return map;
	}

	/**
	 * 从缓存中获取投资人统计数据
	 */
	@Override
	public Map<String, Object> getInvestorCache(String key,String orgId) {
		LOGGER.info("get Investor Stats Cache is null  for key is:[{}]", key);
		PerFormReqBean model = new PerFormReqBean();
		model.setOrgId(orgId);
		return queryInvestorStats(model);
	}
	
	/**
	 * 保存业绩统计数据到缓存
	 */
	@Override
	@CachePut(value = Const.STATS, key = "#key")
	public InvestorCountBean savePerformanceCache(InvestorCountBean bean,String key) {
		LOGGER.info("save Performance Stats Cache ("+key+")");
		return bean;
	}

	/**
	 * 从缓存中获取业绩统计数据
	 */
	@Override
	public InvestorCountBean getPerformanceCache(String key) {
		LOGGER.info("get Performance Stats Cache is null ("+key+") ");
		return null;
	}
	
	/**
	 * 缓存机构存在数据的最早年份
	 */
	@Override
	public String saveEarliestYear(String key,String earliestYear) {
		return earliestYear;
	}
	
	/**
	 * 从缓存中获取数据存在最早年份
	 */
	@Override
	public String getEarliestYear(String key) {
		return "2014";
	}
	
	 /**
     * 投资人数据统计
     * @param model 参数
     */ 	
	public Map<String, Object> queryInvestorStats(PerFormReqBean model) {
		Investor inves = new Investor();
		inves.setRegisterTime(null);
		inves.setOrgId(model.getOrgId());
		Map<String, Object> mapsMap = new HashMap<String, Object>();
		try {
			List<Investor> list = investorDao.queryList(inves);
			//性别map初始化
			Map<String, Integer> mapGender = new HashMap<String, Integer>();
			mapGender.put("未知", 0);
			mapGender.put("男", 0);
			mapGender.put("女", 0);
			//年龄map初始化
			Map<String, Integer> mapAge = new HashMap<String, Integer>();
			mapAge.put("60岁以上", 0);
			mapAge.put("50-60岁", 0);
			mapAge.put("40-50岁", 0);
			mapAge.put("30-40岁", 0);
			mapAge.put("30岁以下", 0);
			mapAge.put("未知", 0);
			//资产map初始化
			Map<String, Double> mapAssets = new HashMap<String, Double>();
			mapAssets.put("1000万以上", 0D);
			mapAssets.put("500-1000万", 0D);
			mapAssets.put("300-500万", 0D);
			mapAssets.put("100-300万", 0D);
			mapAssets.put("100万以下", 0D);
			//省市map初始化
			Map<String, Integer> valProvince = Province.getMapStr();
			Map<String, Integer> valCity = City.getMapStr();
			for (Investor i : list) {
				 //投资人性别分布统计
				Integer gender = i.getGender();
				if ( gender == null) {
						mapGender.put("未知",  mapGender.get("未知")+1);
				}else {
					switch(gender) {
					case 1: mapGender.put("男",  mapGender.get("男")+1);break;
					case 2: mapGender.put("女",  mapGender.get("女")+1);break;
					default: break;
				}
				}
				//投资人年龄分布统计
				Date birthday = i.getBirthday();
				String idcard = i.getIdcard();
				if(birthday != null || idcard != null){
					Date birDate = null;
					if(birthday != null){
						birDate = birthday;
					}else if ( idcard != null) {
						String birthdayStr = idcard.substring(6, 14);
						DateFormat  dateFormat = new SimpleDateFormat("yyyyMMdd");
						birDate =  dateFormat.parse(birthdayStr);
					}
					long time = (new Date().getTime() - birDate.getTime()) / (24 * 60 * 60 * 1000);
					Integer age = (int) (time/365);
			        age = age-age%10;
			        if(age >= 60){
						age = 60;
					}
					else if(age < 60 && age >= 50 ){
						age = 50;
					}
					else if(age < 50 && age >=40 ){
						age = 40;
					}
					else if(age < 40 && age >=30){
						age = 30;
					}
					else if(age < 30){
						age = 20;
					}
					switch(age) {
					case 60: mapAge.put("60岁以上",  mapAge.get("60岁以上")+1);break;
					case 50: mapAge.put("50-60岁",  mapAge.get("50-60岁")+1);break;
					case 40: mapAge.put("40-50岁",  mapAge.get("40-50岁")+1);break;
					case 30: mapAge.put("30-40岁",  mapAge.get("30-40岁")+1);break;
					case 20: mapAge.put("30岁以下",  mapAge.get("30岁以下")+1);break;
					default: break;
					}
				}else{
					mapAge.put("未知",mapAge.get("未知")+1);
				}
				//投资人资产分布统计
				Long asset =  0L;
				asset = investorDao.getInvestorAsset(i.getId());
				if (asset == null) {
					asset =0L;
				}
				asset = asset/10000;
				Integer assetInt = (int) (asset-asset%100);
				int flag = 0;
				if(assetInt > 1000){
					flag = 1000;
				}
				else if(assetInt <= 1000 && assetInt >500){
					flag = 500;
				}
				else if(assetInt <=500 && assetInt >300){
					flag = 300;
				}
				else if(assetInt <= 300 && assetInt >100){
					flag = 100;
				}
				else if(assetInt <= 100 && assetInt > 0){
					flag = 90;
				}
				switch(flag) {
					case 1000: mapAssets.put("1000万以上",  mapAssets.get("1000万以上")+1);break;
					case 500: mapAssets.put("500-1000万",  mapAssets.get("500-1000万")+1);break;
					case 300: mapAssets.put("300-500万",  mapAssets.get("300-500万")+1);break;
					case 100: mapAssets.put("100-300万",  mapAssets.get("100-300万")+1);break;
					case 90: mapAssets.put("100万以下",  mapAssets.get("100万以下")+1);break;
				default: break;
				}
				//投资人地域分布统计
				String province = i.getProvince();
				String city = i.getCity();
				if(province !=null){
					if( Province.get(province) !=null){
						valProvince.put(Province.get(province),valProvince.get(Province.get(province))+1);	
					}
				}
				if (city !=null){
					if( City.get(city) !=null){
						valCity.put(City.get(city),valCity.get(City.get(city))+1);	
					}
				}
			}
			//投资人性别统计数据封装到bean中
			List<InvestorCountBean> allGenderlist = new ArrayList<InvestorCountBean>();
			transMap2BeanEx(mapGender,allGenderlist);
			
			//投资人年龄统计数据封装到bean中
			List<InvestorCountBean> allAgelist = new ArrayList<InvestorCountBean>();
			transMap2BeanEx(mapAge,allAgelist);
			
			//投资人资产统计数据封装到bean中
			List<InvestorCountBean> allAsseteslist = new ArrayList<InvestorCountBean>();
			transMap2Bean(mapAssets,allAsseteslist);
			
			//投资人区域分布数据封装到bean中
			List<InvestorCountBean> allProvincelist = new ArrayList<InvestorCountBean>();
			Integer maxPro = transMap2BeanEx(valProvince,allProvincelist); 
			List<InvestorCountBean> allCitylist = new ArrayList<InvestorCountBean>();
			Integer maxCity = transMap2BeanEx(valCity,allCitylist); 
			
			mapsMap.put("gender", allGenderlist);
			mapsMap.put("age", allAgelist);
			mapsMap.put("assetes", allAsseteslist); 
			mapsMap.put("province", allProvincelist); 
			mapsMap.put("city", allCitylist); 
			mapsMap.put("maxPro", maxPro);
			mapsMap.put("maxCity", maxCity);
			
			//保存机构投资人统计数据到缓存中
			saveInvestorCache(mapsMap,Const.PREFIX_INVESTOR_CACHE_KEY+model.getOrgId());
			
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("query  InvestorStats  data error,msg=[{}] "+e);
		}
		return mapsMap;
	}
	/**
	 * 将Map转换成JavaBean
	 * @param map
	 * @param list
	 */
	private void transMap2Bean(Map<String, Double> map,List<InvestorCountBean> list) {
		//统计数据封装到bean中
		Iterator<?> it = map.entrySet().iterator();
		while (it.hasNext()) {
			InvestorCountBean bean = new InvestorCountBean();
			Entry<?, ?> entry = (Entry<?, ?>) it.next();
			bean.setValue(Double.parseDouble(entry.getValue().toString()));
			bean.setName(entry.getKey().toString());
			list.add(bean);
		}
	}
	
	/**
	 * 将Map转换成JavaBean扩展
	 * @param map
	 * @param list
	 */
	private Integer transMap2BeanEx(Map<String, Integer> map,List<InvestorCountBean> list) {
		//统计数据封装到bean中
		Integer maxValue = -1;
		Iterator<?> it = map.entrySet().iterator();
		while (it.hasNext()) {
			InvestorCountBean bean = new InvestorCountBean();
			Entry<?, ?> entry = (Entry<?, ?>) it.next();
			bean.setValue(Double.parseDouble(entry.getValue().toString()));
			bean.setName(entry.getKey().toString());
			bean.setSelected(false);
			list.add(bean);
			Integer integer = Integer.parseInt(entry.getValue().toString());
			if( integer > maxValue){
				maxValue = integer;
			}
		}
		return maxValue;
	}
}
